package com.lovo.market.common.aspect;

import com.lovo.market.common.enums.CodeEnum;
import com.lovo.market.common.exception.ExpectedException;
import com.lovo.market.common.util.ResultFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.client.HttpClientErrorException;

/**
 * @author MirAi
 * @description 异常处理基类
 * @date 2020/12/15 17:12
 */
public class BaseHandleException {

    /**
     * 异常处理
     *
     * @param t 异常
     * @return 错误信息结果集
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Throwable.class)
    public Object handleException(Throwable t) {

        if (t instanceof ExpectedException) {
            return ResultFactory.fail(((ExpectedException) t).getCodeEnum());
        }

        if (t instanceof HttpClientErrorException) {
            return ((HttpClientErrorException) t).getResponseBodyAsString();
        }

        return ResultFactory.fail(CodeEnum.UNKNOWN_FAIL);
    }
}
